<?php

namespace liketp;

class Log
{
    public static function record($msg, $type = 'info')
    {
        $logDir = App::instance()->getRuntimePath() . 'log' . DS;
        if (is_dir($logDir) == false) mkdir($logDir);

        $fileName = date('Ymd') . '_' . $type . '.log';
        $file = $logDir . $fileName;

        if (is_array($msg)) {
            ob_start();
            print_r($msg);
            $msg = ob_get_clean();
        }
        if (is_object($msg)) {
            ob_start();
            var_dump($msg);
            $msg = ob_get_clean();
        }
        $content = '[' . date('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL;

        $fp = fopen($file, 'a');
        fwrite($fp, $content);
        fclose($fp);

        static::clearFile($logDir, 30);
    }

    public static function clearFile($dir, $max)
    {
        $files = scandir($dir);
        if (count($files) <= $max) return;
        $files = array_filter($files, function ($file) use ($dir) {
            if ($file !== '.' && $file !== '..' && file_exists($dir . $file)) {
                return $file;
            }
        });
        sort($files);
        $needClearFiles = array_slice($files, 0, count($files) - $max);
        foreach ($needClearFiles as $file) {
            unlink($dir . $file);
        }
    }
}
